package kt

import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v7.widget.LinearLayoutManager
import android.widget.SeekBar
import base.BaseActivity
import com.talk.debby.talk.R
import kotlinx.android.synthetic.main.activity_video.*
import android.widget.Toast
import talk.Bean.Video
import talk.Data.Constant
import talk.dapter.VideoAdapter
import talk.listener.OnVideoClick


class VideoActivity : BaseActivity(), Runnable {
    private val handler = Handler()
    private var videos = ArrayList<Video>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)
        initView()
        initData()
    }

    fun initView() {
        //初始化播放器
        videoView.setOnPreparedListener { mp ->
            mp.start()// 播放
            seekBar.max = mp.duration
            dismissProgressDialog()
            Toast.makeText(this, "开始播放！", Toast.LENGTH_LONG).show()
        }
        videoView.setOnCompletionListener {
            Toast.makeText(this, "播放完毕", Toast.LENGTH_SHORT).show()
        }
        //暂停
        iv_pause.setOnClickListener {
            if (videoView.isPlaying)
                videoView.pause()
            else {
                videoView.start()
            }
        }
        //重播
        iv_replay.setOnClickListener { videoView.resume() }
        //进度条
        handler.postDelayed(this, 100)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seek: SeekBar?, progress: Int, p2: Boolean) {
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                videoView.seekTo(p0!!.progress)
            }
        })
        //切换
        rv_videos.layoutManager = LinearLayoutManager(this)
        rv_videos.adapter = VideoAdapter(this, videos, OnVideoClick { changeVideo(it) })
    }

    private fun initData() {
        addList()
    }

    private fun changeVideo(url: String) {
        showProgressDialog("加载中。。。")
        videoView.setVideoURI(Uri.parse(url))
        videoView.start()
    }

    override fun run() {
        seekBar.progress = videoView.currentPosition
        handler.postDelayed(this, 1000)
    }

    private fun addList() {
        videos.add(Video("电场计算题1", Constant.Video1))
        videos.add(Video("高斯定理1", Constant.Video2))
    }

}